<!--安全监督检查表 superviseInspectRpt-->
<template>
  <Layout>
    <Form ref="queryForm" :model="dataToQuery" :label-width="120">
      <Row  class="query-form">
        <Col span="8">
          <FormItem label="二级集团：" prop="order">
            <two-level-org org-code v-model="dataToQuery.twoLevelOrgId" ></two-level-org>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="被检查企业：" prop="order">
            <company-select v-model="dataToQuery.companyName"></company-select>
          </FormItem>
        </Col>
        <Col span="8" v-if="!switchFlag">
          <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
        <Col span="8"  v-else>
          <FormItem label="检查组别：">
            <Select class='' type='text' v-model='dataToQuery.inspectionGroupCategory' style="width: 100%;" multiple>
              <Option v-for="item in igcMap" :value="item.codingCodeId" :key="item.codingCodeId">{{
                  item.codingName
                }}
              </Option>
            </Select>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form">
        <Col span="8">
          <FormItem label="检查时间：" prop="content">
            <DatePicker class="query-form-el" v-model="dataToQuery.inspectionTimeRange" format="yyyy-MM-dd"
                        type="daterange" placement="bottom-end" placeholder="请选择检查时间段"
                        @on-change="(date) => onSelectFieldQueryDateRange(date, 'inspectionTime')"
                        style="width: 100%;"></DatePicker>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="填表时间：" prop="content">
            <DatePicker class="query-form-el" v-model="dataToQuery.createRange" format="yyyy-MM-dd" type="daterange"
                        placement="bottom-start" placeholder="请选择登记时间段" style="width: 100%;"
                        @on-change="(date) => onSelectFieldQueryDateRange(date, 'createDate')"></DatePicker>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="整改状态：" prop="state">
            <Select v-model="dataToQuery.state" style="width: 100%;">
              <Option value="1">未闭环企业</Option>
              <Option value="2">闭环企业</Option>
            </Select>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form">
        <Col span="24">
          <div style="float: right;">
            <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
            <Button @click="reset" class="ivu-btn-reset">重置</Button>
            <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
          </div>
        </Col>
      </Row>
      <Row class="query-form">
        <Col span="24">
          <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
          <Button type="primary" class="ivu-btn-add" icon="md-cloud-download" @click="exportFormSubmit" :loading="exportLoading">导出</Button>
        </Col>
      </Row>
    </Form>
    <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!" @on-selection-change='getSelectRows' @on-sort-change="querySort"
           :loading='pageStatus.loading' show-summary :summary-method="handleSummary"
           border :columns="columns1" :data="dataTable">
    </Table>
    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
              @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer
              show-elevator/>
      </Col>
    </Row>
    <Modal title="安全监督检查表" :transfer=false :mask-closable="false" v-model="dialogShow" v-if="dataToView && dialogShow"
           :width=1000 :styles="{height:'748px'}" class-name='limit-height-dialog' @on-cancel="handleCancel">
      <Row>
        <Col span="24">
          <Form ref="dialogForm" :class="mode === 'view'?'modal-view-detail':'rpt-form'" :show-message="false"
                :model="dataToView" :rules="mode === 'view'?{}:ruleCustom" :label-width="mode === 'view'?170:null"
                :label-position="mode === 'view'?'right':'top'">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label='被检查企业：' prop='companyName'>
                  <div v-if="mode === 'view'">{{ dataToView.companyName }}</div>
                  <cascader-dom v-else ref='orgCascader' @setOrgInfo='setCompanyId' @setOrgname="setCompanyName"
                                :orgTree="true" :currentOrgId="dataToView.companyId"
                                :setCurrentName="{label:dataToView.companyName,value:dataToView.companyId}"></cascader-dom>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='二级集团：' prop='belongOrgName'>
                  <div v-if="mode === 'view'">{{ dataToView.belongOrgName }}</div>
                  <Input v-else class='' type='text' v-model='dataToView.belongOrgName' readonly></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='检查时间：' prop='inspectionTime'>
                  <div v-if="mode === 'view'">{{ renderViewDate(dataToView.inspectionTime) }}</div>
                  <DatePicker v-else type="date" placeholder="请选择日期" style="width: 100%"
                              v-model='dataToView.inspectionTime' :options="options"
                              :editable='false'></DatePicker>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='检查组别：' prop='inspectionGroupCategory'>
                  <div v-if="mode === 'view'">
                    {{
                      this.igcMap[dataToView.inspectionGroupCategory] && this.igcMap[dataToView.inspectionGroupCategory].codingName
                    }}
                  </div>
                  <Select v-else class='' placeholder="请选择检查组别" type='text'
                          v-model='dataToView.inspectionGroupCategory'>
                    <Option v-for="item in igcMap" :value="item.codingCodeId" :key="item.codingCodeId">
                      {{ item.codingName }}
                    </Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='检查组人员：' prop='rummager'>
                  <div v-if="mode === 'view'">{{ dataToView.rummager }}</div>
                  <Input v-else class='' type='text' v-model='dataToView.rummager'></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='检查内容：(不少于10个字符)' prop='contentIssue'>
                  <div v-if="mode === 'view'">{{ dataToView.contentIssue }}</div>
                  <Input v-else class='' type='text' placeholder="检查内容不少于10个字符"
                         v-model='dataToView.contentIssue'></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='发现问题数量：' prop='issueCount'>
                  <div v-if="mode === 'view'">{{ dataToView.issueCount }}</div>
                  <InputNumber v-else class='w' :min="0" placeholder="请填写发现问题数量" type='text'
                               :readonly="this.currentUser.loginId != 'superadmin'"
                               v-model='dataToView.issueCount'></InputNumber>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='填表人电话：' prop='createMobile'>
                  <div v-if="mode === 'view'">{{ dataToView.createMobile }}</div>
                  <Input v-else type='text' v-model='dataToView.createMobile'></Input>
                  <!--<Input v-if="mode === 'edit'" type='text' v-model='dataToView.createMobile' :readonly="this.currentUser.userId === dataToView.createUserId ? false : 'readonly'"></Input>-->
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='整改完成问题数量：' prop='issueCompletionCount'>
                  <div v-if="mode === 'view'">{{ dataToView.issueCompletionCount }}</div>
                  <InputNumber v-else class='w' :readonly="this.currentUser.loginId != 'superadmin'" :min="0"
                               placeholder="请填写整改完成问题数量" type='text'
                               v-model='dataToView.issueCompletionCount'></InputNumber>
                </FormItem>
              </Col>
            </Row>
          </Form>
          <Row type="flex" justify="space-around" class="code-row-bg query-form" v-if="mode != 'view'">
            <Col span="23">
              <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfoItem">新增</Button>
              <Upload class="importDanger" :action="uploadProQuestion" :show-upload-list="false"
                      :on-success="uploadInfoItem"
                      accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                      :format="['xlsx','xls']"
                      :headers='{"Authorization": token}'>
                <Button class="ivu-btn-add" type="ghost" icon="md-cloud-upload">导入</Button>
              </Upload>
              <Button size="large" class="ivu-btn-add" icon="md-cloud-download" @click="downloadItemMod">导入模版下载</Button>
            </Col>
          </Row>

          <Row type="flex" justify="space-around" class="code-row-bg">
            <Col span="23">
              <EnProQuestionDetail v-if="mode != 'view'" ref="question" @addSubmit="submitItem" @query="queryItems"
                                   :data-table="dataTableItem" @delete="deleteItem"
                                   :loading="loadingItems"></EnProQuestionDetail>

              <Table v-else ref='table1' :height="300" no-data-text="没有查询到相关数据!"
                     border :columns="columns2" :data="dataTableItem">
              </Table>
            </Col>
          </Row>
          <Form ref="dialogForm1" :class="mode === 'view'?'modal-view-detail':'rpt-form'" :show-message="false"
                :model="dataToView" :rules="mode === 'view'?{}:ruleCustom" :label-width="mode === 'view'?170:null"
                :label-position="mode === 'view'?'right':'top'">
            <Row type="flex" justify="space-around" class="code-row-bg" style="margin-top: 10px">
              <Col span="23">
                <FormItem v-if="mode === 'view'" label="相关附件：">
                  <div v-show="dataToView.fileIdFiles.length>0" v-for="item in dataToView.fileIdFiles">
                    <a @click="downloadFile(item)"><span style="color: #3399ff;margin-left: 5px">{{
                        item.fileName
                      }}</span></a>
                  </div>
                </FormItem>
                <FormItem v-else label="上传附件：">
                  <div>
                    <Upload ref="upload"
                            :before-upload="(file) => { beforeUpload(file, 'fileId') }"
                            :show-upload-list="true"
                            :max-size="10240"
                            multiple
                            type="drag"
                            :action="fileUrl">
                      <div style="padding: 20px">
                        <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                        <p>点击将文件拖拽到这里上传</p>
                      </div>
                    </Upload>
                  </div>
                  <div v-show="dataToView.fileIdFiles.length>0" v-for="item in dataToView.fileIdFiles" :key="item.id">
                    <a @click.prevent="downloadFile(item)">{{ item.fileName }}</a>
                    <Button type="text" icon="md-trash" @click="removeFile(item.id, 'fileId')"
                            style="margin-left: 20px;margin-bottom: 3px"/>
                  </div>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='填表人：' prop='registrant'>
                  <div v-if="mode === 'view'">{{ dataToView.createUserName }}</div>
                  <Input v-else type='text' v-model='dataToView.createUserName' readonly></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='填表时间：' prop='registTime'>
                  <div v-if="mode === 'view'">{{ renderViewDate(dataToView.createDate) }}</div>
                  <DatePicker v-else type="date" placeholder="请选择日期" class="w" v-model='dataToView.createDate'
                              readonly></DatePicker>
                </FormItem>
              </Col>
            </Row>
          </Form>
          <!--            <Row type="flex" justify="space-around" class="code-row-bg">
                        <Col span="23">
                          <FormItem label='问题及整改要求：' prop='issueRectificationRequest'>
                            <div v-if="mode === 'view'">{{ dataToView.issueRectificationRequest }}</div>
                            <Input v-else class='' type='text' v-model='dataToView.issueRectificationRequest'></Input>
                          </FormItem>
                        </Col>
                      </Row>-->
          <!--            <Row type="flex" justify="space-around" class="code-row-bg">
                        <Col span="23">
                          <FormItem label='问题整改完成情况：' prop='issueCompletion'>
                            <div v-if="mode === 'view'">{{ dataToView.issueCompletion }}</div>
                            <Input v-else class='' type='text' v-model='dataToView.issueCompletion'></Input>
                          </FormItem>
                        </Col>
                      </Row>-->
          <!--            <Row type="flex" justify="space-around" class="code-row-bg">
            <Col span="11">
              <FormItem label='整改完成问题数量：' prop='issueCompletionCount'>
                <div v-if="mode === 'view'">{{ dataToView.issueCompletionCount }}</div>
                <InputNumber v-else class='w' :min="0" placeholder="请填写整改完成问题数量" type='text'
                             :readonly="true" v-model='dataToView.issueCompletionCount'></InputNumber>
              </FormItem>
            </Col>
            <Col span="11">

            </Col>
          </Row>-->


        </Col>
      </Row>
      <div slot="footer">
        <Button v-if="mode != 'view'" type="primary" class='ivu-btn-save' @click="submit('dialogForm')">确定</Button>
        <Button v-if="mode != 'view'" type="primary" class='ivu-btn-cancel' @click="handleCancel">取消</Button>
        <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
      </div>
    </Modal>
    <Modal title="安全监督检查问题详情" :transfer=false v-model="modal3" class="modal-view-detail" :width=700
           :styles="{top: '10px'}">
      <Form ref="viewForm" :label-width="100">
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="问题类别：">
              <div>
                {{ dataToViewItem.problemCategoryName }}
              </div>
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="检查时间：">
              {{ renderViewDate(dataToViewItem.checkTime) }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="完成时限：">
              {{ renderViewDate(dataToViewItem.completeTime) }}
            </FormItem>
          </Col>
          <Col span="11">

          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="问题描述：">
              {{ dataToViewItem.problemDesc }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label='整改方案：' prop='rectifyPlan'>
              {{ dataToViewItem.rectifyPlan }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label='当前进展描述：' prop='completion'>
              {{ dataToViewItem.completion }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="整改附件：">
              <div v-show="dataToViewItem.idFiles.length>0" v-for="(item,index) in dataToViewItem.idFiles">
                <a @click="downloadFiles(item,index)"><span style="color: #3399ff;margin-left: 5px">{{
                    item.fileName
                  }}</span></a>
                <Progress v-show="uploadListVisible[index]" :percent="uploadListPercent[index]"></Progress>
              </div>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="modal3=false">关闭</Button>
      </div>
    </Modal>
    <Modal title="导入出错" :transfer=false v-model="modelFail" class="modal-view-detail" :width=800
           :styles="{top: '10px'}">
      <Form ref="modelFail" :label-width="100">
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <Table ref='tableFail' :height="400" no-data-text="没有查询到相关数据!"
                   border :columns="columnsFail" :data="dataTableFail">
            </Table>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg" style="margin-top: 10px">
          <Col span="23" style="color: red">
            <div>导入须知:</div>
            <div>1、请使用系统提供的模版导入</div>
            <div>2、如出现时间有误,请统一调整 =》例：2022/01/01</div>
            <div>3、问题类别请使用模版下拉框中提供的</div>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="modelFail=false">关闭</Button>
      </div>
    </Modal>
  </Layout>
</template>

<script>
import {Api} from '@/api/index.js'
import pageCommonFunction from '@/components/pageCommonFunction.js'
import {sessionStorage} from '@/common/cacheUtils.js'
import EnProQuestionDetail from "./EnProQuestionDetail";
import _deepclone from 'lodash/cloneDeep'

var cascaderDom = () => import('@/components/cascader-dom.vue');
export default {
  components: {
    cascaderDom, EnProQuestionDetail
  },
  data() {
    return {
      ...this.createCommonDataField(),
      dataTableItem: [],
      dataToViewItem: {},
      loadingItems: false,
      modal3: false,
      modelFail: false,
      dataTableFail: [],
      columnsFail: [
        {
          title: 'excel行号', width: 80, fixed: 'left', align: 'center', key: 'rowNum'
        },
        {
          key: 'errorMsg', title: '错误提示', fixed: 'left', align: 'center', minWidth: 200, tooltip: true,
          render: (h, params) => {
            return h('div', [
              h('A', {
                props: {type: 'primary', size: 'small'},
                style: {color: 'red'},
              }, params.row.errorMsg),
            ]);
          }
        },
        {key: 'problemDesc', title: '问题描述', align: 'center', minWidth: 200, tooltip: true},
        {key: 'problemCategoryName', title: '问题类别', align: 'center', minWidth: 150},
        {key: 'rectifyPlan', title: '整改方案描述', align: 'center', minWidth: 200, tooltip: true},
        {key: 'completion', title: '当前进展描述', align: 'center', minWidth: 200, tooltip: true},
        {key: 'checkTime', title: '检查时间', align: 'center', minWidth: 150, render: this.renderCellDate},
        {
          key: 'completeTime',
          title: '完成时限',
          fixed: 'left',
          align: 'center',
          minWidth: 150,
          render: this.renderCellDate
        },
      ],
      columns2: [
        {
          title: '序号', width: 80, fixed: 'left', align: 'center', render: (h, params) => {
            return h('span', params.index + 1);
          }
        },
        {key: 'problemDesc', title: '问题描述', align: 'center', minWidth: 200, tooltip: true},
        {key: 'problemCategoryName', title: '问题类别', align: 'center', minWidth: 150},
        {key: 'rectifyPlan', title: '整改方案描述', align: 'center', minWidth: 200, tooltip: true},
        {key: 'completion', title: '当前进展描述', align: 'center', minWidth: 200, tooltip: true},
        {key: 'checkTime', title: '检查时间', align: 'center', minWidth: 150, render: this.renderCellDate},
        {
          key: 'completeTime',
          title: '完成时限',
          fixed: 'left',
          align: 'center',
          minWidth: 150,
          render: this.renderCellDate
        },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 160,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('A', {
                props: {type: 'primary', size: 'small'},
                style: {fontSize: '14px',},
                on: {
                  click: () => {
                    this.viewItem(params)
                  }
                }
              }, '详情'),
            ]);
          }
        }
      ],
      columns1: [
        {type:'expand', width:30,
          fixed: 'left',
          _disableExpand:true,
          render:(h,params)=>{
            return h('Table',{
              props: {
                columns: [
                  {
                    title: '序号', width: 80, fixed: 'left', align: 'center', render: (h, params) => {
                      return h('span', params.index + 1);
                    }
                  },
                  {key: 'problemDesc', title: '问题描述', align: 'center', minWidth: 200, tooltip: true},
                  {key: 'problemCategoryName', title: '问题类别', align: 'center', minWidth: 150},
                  {key: 'rectifyPlan', title: '整改方案描述', align: 'center', minWidth: 200, tooltip: true},
                  {key: 'completion', title: '当前进展描述', align: 'center', minWidth: 200, tooltip: true},
                  {key: 'checkTime', title: '检查时间', align: 'center', minWidth: 150, render: this.renderCellDate},
                  {
                    key: 'completeTime',
                    title: '完成时限',
                    align: 'center',
                    minWidth: 150,
                    render: this.renderCellDate
                  }, {
                    key: 'finishTime',
                    title: '完成时间',
                    align: 'center',
                    minWidth: 150,
                    render: this.renderCellDate
                  },
                ],//表头
                data: params.row.items,//内部表格展示的数据
              },
            })//我这里使用的是表格，大家也可以根据自己的实际情况更换别的组件
          }
        },
        {
          key: 'index', title: '序号', width: 80, fixed: 'left', align: 'center', render: (h, params) => {
            if (params.row.id === '-1') return h('span', "汇总");
            return h('span', (params.index - 1) + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },
        {key: 'belongOrgName', fixed: 'left', title: '二级集团', align: 'center', width: 200},
        {key: 'companyName', title: '被检查企业', fixed: 'left', align: 'center', width: 200},
        {key: 'inspectionTime', title: '检查时间', align: 'center', width: 150, render: this.renderCellDate, sortable: 'custom'},
        {
          key: 'inspectionGroupCategory', title: '检查组别', align: 'center', width: 120, render: (h, params) => {
            return h('span', this.igcMap && this.igcMap[params.row.inspectionGroupCategory] && this.igcMap[params.row.inspectionGroupCategory].codingName)
          },
        },
        {key: 'rummager', title: '检查组人员', align: 'center', width: 200},
        {key: 'issueCount', title: '问题数量', align: 'center', width: 100},
        {key: 'issueCompletionCount', title: '整改完成问题数量', align: 'center', width: 150},
        {key: 'contentIssue', title: '检查内容', align: 'center', width: 200, tooltip: true},
        // {key: 'issueRectificationRequest', title: '问题及整改要求', align: 'center', width: 200, tooltip: true},
        // {key: 'issueCompletion', title: '问题整改完成情况', align: 'center', width: 200, tooltip: true},
        // {key: 'issueCompletionTime', title: '整改完成时间', align: 'center', width: 150, render: this.renderCellDate},
        {key: 'createDate', title: '填表时间', align: 'left', width: 120, render: this.renderCellDate, sortable: 'custom'},
        this.getActionColumns((params) => {
          return params.row.id === '-1';
        })
      ],
      ruleCustom: {
        companyName: [{required: true, message: '请填写企业名称', trigger: 'change'}],
        inspectionTime: [{required: true, message: '请填写检查时间', trigger: 'change', type: 'date'}],
        inspectionGroupCategory: [{required: true, message: '请填写检查组别', trigger: 'change'}],
        createMobile: [{
          pattern: /^((0\d{2,3}-\d{7,8})|(1[3675849]\d{9}))$/,
          required: true,
          message: '请填写填表人电话',
          trigger: 'change'
        }],
        rummager: [{
          // required: true, message: '请填写检查组人员', trigger: 'change'
          validator: (rule, value, callback) => {
            if (this.dataToView.rummager == null || this.dataToView.rummager == '' || this.dataToView.rummager == undefined) {
              callback(' ')
            } else {
              if ((/^[0-9]+(.[0-9]+)?$/.test(this.dataToView.rummager))) {
                callback(' ');
              } else {
                callback()
              }
            }
          },
          required: true,
          trigger: 'change'
        }],
        contentIssue: [{required: true, message: '请填写检查内容', trigger: 'change'},
          {pattern: /^.{10,}$/, message: '检查内容不少于10个字符', trigger: 'change'}],
        // issueCount: [ { pattern: /^([0-9][0-9]*)?$/, required: true, message: '请填写问题数量,必须为数字', trigger: 'change, blur',type: 'number'}],
        // issueCompletionCount: [ { pattern: /^([0-9][0-9]*)?$/, required: true, message: '请填写整改问题完成数量,必须为数字', trigger: 'change, blur',type: 'number'}]
      },
      tableHeight: 10,
      igcMap: {},
      // api
      token: sessionStorage('token').get('Authorization'),
      queryUrl: Api.querySuperviseInspect + '/2',
      exportUrl: Api.exportSuperviseInspect + '/2',
      deleteUrl: Api.deleteSuperviseInspect,
      bthDeleteUrl: Api.batchDeleteSuperviseInspect,
      getUrl: Api.getSuperviseInspect,
      updateUrl: Api.updateSuperviseInspect,
      saveUrl: Api.saveSuperviseInspect + '/2',
      downloadMod: Api.downloadSuperviseInpsect + '/2',
      uploadProQuestion: Api.uploadProQuestion + '/2',
      options: {
        disabledDate(date) {
          return date && date.valueOf() >= new Date();
        }
      },
    }
  },
  async mounted() {
    await this.$http.get(Api.queryCodeDetailBySortId + '/IGC-000002', {params: {}}).then((res) => {
      this.igcMap = this.dictListToMap(res.data.data);
    });
    if (this.$route.query.id) {
      this.dataToQuery.id = this.$route.query.id;
    }
    this.setSumTableHeight();
    let date = this.setInspectionTimeRange();
    this.onSelectFieldQueryDateRange(date, 'inspectionTime');
    this.query();
  },
  methods: {
    ...pageCommonFunction,
    setInspectionTimeRange() {
      let date1 = new Date();
      let year1 = date1.getFullYear();
      let firstMonth = year1 + '-' + '01' + '-' + '01';
      let firstDate = new Date(Date.parse(firstMonth))
      this.$set(this.dataToQuery.inspectionTimeRange, 0, firstDate);
      let date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      if (month < 10) {
        month = "0" + month;
      }
      if (day < 10) {
        day = "0" + day;
      }
      ;
      let currentdate = year + '-' + month + '-' + day;
      let currentDate = new Date(Date.parse(currentdate))
      this.$set(this.dataToQuery.inspectionTimeRange, 1, currentDate);
      return [firstMonth, currentdate]

    },
    uploadInfoItem(response) {
      if (response.status == '200') {
        response.data.forEach(item => {
          this.dataTableItem.push(item);
        })
      } else {
        this.dataTableFail = [];
        this.dataTableFail = response.data;
        this.modelFail = true;
      }
      this.$set(this.dataToView, 'issueCount', this.dataTableItem.length)
    },
    downloadItemMod() {
      let url = this.downloadMod
      this.$http.get(url, {
        responseType: 'blob'      //告诉服务器我们需要的响应格式
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = "安全监督检查问题导入模版.xlsx" //标题
        aLink.click()
        document.body.appendChild(aLink)
      })
    },
    async viewItem(params) {
      this.dataToViewItem = _deepclone(params.row);
      await this.getFilesItem('id', 'EnQuestionDetailForApproval');
      this.modal3 = true;
    },
    queryItems() {
      this.loadingItems = true;
      this.$http.get(Api.querysuperviseInspectItems + this.dataToView.id).then((res) => {
        if (res.data.status == '200') {
          this.loadingItems = false;
          this.dataToView.items = res.data.data;
          this.dataTableItem = res.data.data;
        }else{
          this.$Message.error(res.data.msg);
        }
        this.loadingItems = false;

      }).catch(e =>{
        this.$Message.error(res.data.msg);
        console.log(e);
      })
    },
    beforeViewDialogOpen(data) {
      this.dataTableItem = data.row.items;
    },
    beforeEditDialogOpen(data) {
      this.dataTableItem = data.row.items;
    },
    addInfoItem() {
      this.$refs.question.add(this.dataToView.inspectionTime);
    },
    async getFilesItem(filedName, type) {
      if (this.dataToViewItem[filedName]) {
        let url = this.fileUrl + '/' + this.dataToViewItem[filedName] + '/files/' + type.split('/')[0]
        await this.$http.get(url).then((res) => {
          if (res.data.result == "success") {
            this.$set(this.dataToViewItem, filedName + 'Files', res.data.data)
            let index = 0;
            res.data.data.forEach(item => {
              this.uploadListPercent[index] = 0;
              this.uploadListVisible[index] = false;
              this.uploadListVisible[item.id] = false;
              index++;
            })
          }
        });
      }
    },
    createEmptyDataToAdd() {
      this.dataTableItem = [];
      return {
        fileId: this.get_uuid(),
        fileIdFiles: [],
        issueCompletionCount: 0,
        issueCount: 0,
        createMobile: sessionStorage('userId').getObject('userId').mobileNumber,
      }
    },
    deleteItem(i) {
      this.dataTableItem.splice(i, 1);
      this.dataToView.issueCount = this.dataTableItem.length
    },
    deleteData(params) {
      this.deleteDateAjax(params);
    },
    submitItem(data) {
      let _this = this;
      if (data.state == 'OPEN'){
        _this.dataToView.issueCompletionCount += 1
      }
      if (data.addMod) {
        _this.dataTableItem.push(data);
        _this.dataToView.issueCount = _this.dataTableItem.length
      } else {
        _this.dataTableItem.splice(data.index, 1, data);
      }
    },
    queryAjax() {
      this.pageStatus.loading = true
      let data = {
        startPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
        conditions: this.dataToQuery
      };

      this.$http.post(this.queryUrl, data).then((res) => {
        if (res.data.status === 201) {
          this.$Message.error(res.data.msg);
        }
        this.dataTable = res.data.data.data;
        // this.dataTable.unshift(res.data.data.total);
        this.pagedata.total = res.data.data.totalSize;
        this.pageStatus.loading = false
      }).catch(e => {
        this.$Message.error("数据获取失败")
        this.pageStatus.loading = false
      })
    },
    query() {
      this.queryAjax();
    },
    submit(name) {
      if (this.dataToView.issueCompletionCount == '') this.dataToView.issueCompletionCount = 0;
      if (this.dataToView.issueCount == '') this.dataToView.issueCount = 0;
      this.submitAjax(name);
    },
    submitAjax(name) {
      let _this = this;
      if (this.pageStatus.sending) return
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.$Modal.confirm({
            title: '提示',
            content:  '<p>是否要提交？</p>',
            onOk: () => {
              let url = this.mode === 'add' ? this.saveUrl : this.updateUrl;
              this.pageStatus.sending = true
              this.dataTableItem.forEach(item => {
                item.companyId = _this.dataToView.companyId;
                item.accountType = '1';
              })
              _this.dataToView.items = this.dataTableItem;
              let successHandle = (res) => {
                if (res.data.status === 200) {
                  this.$Message.success(this.mode === 'add' ? '添加成功' : '修改成功');
                  this.dialogShow = false;
                  this.query()
                } else if (res.data.status === 201) {
                  this.$Message.error(res.data.msg);
                }
                this.pageStatus.sending = false
              }
              let failedHandle = e => {
                this.$Message.error(this.mode === 'add' ? '添加失败' : '修改失败')
                this.pageStatus.sending = false
              }
              if (this.mode === 'add') {
                this.$http.post(url, this.dataToView).then(successHandle).catch(failedHandle)
              } else {
                this.$http.put(url, this.dataToView).then(successHandle).catch(failedHandle)
              }

            },
            onCancel: () => {
            }
          });
        } else {
          this.$Message.error('请填报完整!');
        }
      })
    },
    switchQuery(flag) {
      this.switchFlag = flag;
      if (!this.switchFlag) {
        this.tableHeight = this.tableHeight + 88;
      } else {
        this.tableHeight = this.tableHeight - 88;
      }
    },
    async afterDataToViewInit() {
      await this.getFiles('fileId');
    },
    exportFormSubmit() {
      let token = sessionStorage('token').get('Authorization');
      this.dataToQuery.token = token
      this.dataToQuery.exportPerson = this.currentUser.userName;
      this.dataToQuery.exportDate = new Date();
      this.dataToQuery.exportPhone = this.currentUser.mobileNumber;
      this.downloadTable({
        formData: this.dataToQuery,
        action: this.exportUrl,
        method: 'get'
      })
    },
    createFormAndSubmit({formData, action = '', method = 'post', target = '_blank'}) {
      var dlform = document.createElement('form')
      dlform.style = 'display:none;'
      dlform.method = method
      dlform.action = action
      dlform.target = ''
      for (var key in formData) {
        var data = formData[key]
        if (data instanceof Array) {
          let data1 = new Array()
          for (var i = 0, il = data.length; i < il; i++) {
            data1[i] = data[i]
          }
          createInput(key, data1)
        } else {
          createInput(key, data)
        }
      }
      document.body.appendChild(dlform)
      dlform.submit()
      document.body.removeChild(dlform)

      function createInput(key, data) {
        var hdnFilePath = document.createElement('input')
        hdnFilePath.type = 'hidden'
        hdnFilePath.name = key
        hdnFilePath.value = data
        dlform.appendChild(hdnFilePath)
      }
    },
    querySort({column, key, order}){
      this.dataToQuery.order = order;
      this.dataToQuery.key = key;
      this.queryAjax();
    },
    handleSummary({ columns, data }){
      let temp = JSON.parse(JSON.stringify(data));
      temp.splice(0, 1);
      const sums = {};
      columns.forEach((column, index) => {
        const key = column.key;
        if (index === 1) {
          sums[key] = {
            key,
            value: '合计'
          };
          return;
        }
        const values = temp.map(item => Number(item[key]));
        if (!values.every(value => isNaN(value))) {
          const v = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[key] = {
            key,
            value: v
          };
        } else {
          sums[key] = {
            key,
            value: ''
          };
        }
      })
      return sums;
    }
  },
  watch: {},

}
</script>

<style lang='css' scoped>
.rpt-form {
}

/deep/ .rpt-form .query-form-el {
  width: 100%;
}

.importDanger {
  display: inline-block
}
</style>
